#include "widget.h"
#include "ui_widget.h"
#include <QIntValidator>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    timer = new QTimer;

    QIntValidator *aIntValidator = new QIntValidator;
    aIntValidator->setRange(0, 600);
    ui->secEdit->setValidator(aIntValidator);

    connect(ui->timeEdit, &QDateTimeEdit::dateTimeChanged, this, &Widget::dateTimeChanged);
    connect(ui->dateEdit, &QDateTimeEdit::dateTimeChanged, this, &Widget::dateTimeChanged);
    connect(ui->dateTimeEdit, &QDateTimeEdit::dateTimeChanged, this, &Widget::dateTimeChanged);

    connect(timer, &QTimer::timeout, this, [=] {
        mSec++;
        if ((mSec % 1000) == 0) {
            sec--;
            ui->minLcd->display(QString("%1").arg(sec/60));
            ui->secLcd->display(QString("%1").arg(sec%60));
            if (sec == 0) {
                timer->stop();
                ui->startTimerBtn->setEnabled(true);
                ui->stopTimerBtn->setEnabled(false);
                return ;
            }
        }
        ui->minSecLcd->display(QString::asprintf("%02d", (999-(mSec%1000))/10));
    });

    on_calendar_selectionChanged();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_getTimeBtn_clicked()
{
    QDateTime dateTime = QDateTime::currentDateTime();
    ui->timeEdit->setTime(dateTime.time());
    ui->dateEdit->setDate(dateTime.date());
    ui->dateTimeEdit->setDateTime(dateTime);
}


void Widget::on_startTimerBtn_clicked()
{
    sec = ui->secEdit->text().toInt();
    if (sec > 0) {
        mSec = 0;
        timer->start(1);
        ui->startTimerBtn->setEnabled(false);
        ui->stopTimerBtn->setEnabled(true);
        ui->minLcd->display(QString("%1").arg(sec/60));
        ui->secLcd->display(QString("%1").arg(sec%60));
    }
}


void Widget::on_stopTimerBtn_clicked()
{
    timer->stop();
    ui->startTimerBtn->setEnabled(true);
    ui->stopTimerBtn->setEnabled(false);
}


void Widget::dateTimeChanged(const QDateTime &dateTime)
{
    const char *name = sender()->metaObject()->className();
    QString className = QString("%1").arg(name);
    if (className == "QTimeEdit") {
        QDateTime currentDateTime = ui->dateTimeEdit->dateTime();
        currentDateTime.setTime(dateTime.time());
        ui->dateTimeEdit->setDateTime(currentDateTime);
    } else if (className == "QDateEdit") {
        QDateTime currentDateTime = ui->dateTimeEdit->dateTime();
        currentDateTime.setDate(dateTime.date());
        ui->dateTimeEdit->setDateTime(currentDateTime);
    } else if (className == "QDateTimeEdit") {
        ui->dateEdit->setDate(dateTime.date());
        ui->timeEdit->setTime(dateTime.time());
    }
}


void Widget::on_calendar_selectionChanged()
{
    ui->crtCalendar->setText(ui->calendar->selectedDate().toString("yyyy年MM月dd日"));
}

